<script setup lang="ts">
import { ref } from 'vue'
import { getDeptAndSub } from '@/services/medicalDept'
import { getOnlineDoctorList } from '@/services/doctor'
import type { OnlineDoctorInfo } from '@/types/doctor'
import { onLoad } from '@dcloudio/uni-app'
import { createVideoDiagnose, videoMockPay, checkFace } from '@/services/videoDiagnose'
import { generateRandomDigitString } from '@/utils/randomString'
import dayjs from 'dayjs'

const deptSub = ref('全部诊室')
const DeptSubPicker = ref()
const showDeptSubPicker = ref(false)
const deptSubColumns = ref<string[][]>([])
const deptSubColumnsData = ref<string[][]>([])
const changeDeptSub = (e: any) => {
  const {
    columnIndex,
    value,
    values, // values为当前变化列的数组内容
    index,
    // 微信小程序无法将picker实例传出来，只能通过ref操作
    picker = DeptSubPicker.value,
  } = e
  // 当第一列值发生变化时，变化第二列(后一列)对应的选项
  if (columnIndex === 0) {
    // picker为选择器this实例，变化第二列对应的选项
    picker.setColumnValues(1, deptSubColumnsData.value[index])
  }
}
const confirmDeptSub = (e: any) => {
  showDeptSubPicker.value = false
  deptSub.value = e.value[1]
  //TODO 加载在线医生列表
  loadOnlineDoctorList()
}

const job = ref('全部医师')
const showJobPicker = ref(false)
const jobColumns = ref([['全部医师', '主任医师', '副主任医师', '主治医师', '副主治医师']])
const confirmJob = (e: any) => {
  showJobPicker.value = false
  job.value = e.value[0]
  //TODO 加载在线医生列表
  loadOnlineDoctorList()
}

//医生列表
const doctor = ref<OnlineDoctorInfo[]>([])
const minioUrl = 'http://114.132.57.246:9000/hospital'
const createVideoDiagnoseHandle = (doctorId: number) => {
  uni.showModal({
    title: '提示信息',
    content: '是否预约挂号',
    confirmText: '确定',
    cancelText: '取消',
    complete: (res) => {
      if (res.confirm) {
        checkFace().then((res) => {
          let result = res.result
          if (result == '不存在面部模型') {
            uni.showModal({
              title: '提示消息',
              content: '挂号需要人脸识别验证身份，你还没有录入面部信息，是否立即采集面部信息？',
              confirmText: '录入',
              success: function (resp) {
                if (resp.confirm) {
                  //跳转到面部采集页面，录入面部信息
                  uni.navigateTo({
                    url: '/user/face_camera/face_camera?mode=create',
                  })
                }
              },
            })
          } else if (result == '当日没有人脸验证记录') {
            uni.showModal({
              title: '提示消息',
              content: '每天第一次挂号之前，需要核验面部信息，以便确保是您本人挂号',
              confirmText: '验证',
              success: function (resp) {
                if (resp.confirm) {
                  //跳转到面部采集页面，验证面部信息
                  uni.navigateTo({
                    url: '/user/face_camera/face_camera?mode=verificate',
                  })
                }
              },
            })
          } else {
            createVideoDiagnose({ doctorId }).then((res) => {
              let result = res.result
              let flag = result.flag
              if (!flag) {
                uni.showToast({
                  icon: 'none',
                  title: '医生在问诊中，请稍后再试',
                })
              } else {
                uni.showToast({
                  icon: 'success',
                  title: '挂号成功请付款',
                })
                setTimeout(function () {
                  let videoDiagnoseId = result.videoDiagnoseId
                  let expectStart = result.expectStart
                  let expectEnd = result.expectEnd
                  uni.showModal({
                    title: '提示信息',
                    content: '确认挂号并支付？',
                    confirmText: '模拟支付',
                    cancelText: '取消',
                    success: async (res) => {
                      if (res.confirm) {
                        let data = {
                          outTradeNo: result.outTradeNo,
                          transactionId: generateRandomDigitString(dayjs().format('YYYYMMDD'), 12),
                        }
                        await videoMockPay(data).then((res) => {
                          if (res.result) {
                            uni.showToast({
                              icon: 'success',
                              title: '付款成功',
                            })
                            setTimeout(() => {
                              uni.navigateTo({
                                url: `/video_diagnose/prepare_diagnose/prepare_diagnose?videoDiagnoseId=${videoDiagnoseId}&expectStart=${expectStart}&expectEnd=${expectEnd}&doctorId=${doctorId}`,
                              })
                            }, 1500)
                          } else {
                            uni.showToast({
                              icon: 'none',
                              title: '付款异常，请联系客服',
                            })
                          }
                        })
                      } else if (res.cancel) {
                        uni.showToast({
                          icon: 'none',
                          title: '取消支付',
                        })
                      }
                    },
                  })
                }, 1500)
              }
            })
          }
        })
      }
    },
  })
}

//加载诊室列表
const loadDeptAndSub = () => {
  getDeptAndSub().then((res) => {
    let result = res.result
    let i = 0
    let deptList = []
    let firstSubList = []
    let subList = []
    for (let key in result) {
      ++i
      if (i == 1) {
        for (let item of result[key]) {
          firstSubList.push(item.subName)
        }
      }
      let temp = []
      for (let item of result[key]) {
        temp.push(item.subName)
      }
      deptList.push(key)
      subList.push(temp)
    }
    deptSubColumns.value = [deptList, firstSubList]
    deptSubColumnsData.value = subList
  })
}

//加载在线医生列表
const loadOnlineDoctorList = () => {
  let data = {
    subName: deptSub.value == '全部诊室' ? null : deptSub.value,
    job: job.value == '全部医师' ? null : job.value,
  }
  getOnlineDoctorList(data).then((res) => {
    let result = res.result
    for (let one of result) {
      one.photo = `${minioUrl}/${one.photo}`
      one.price = one.price + '元'
    }
    doctor.value = result
  })
}

onLoad(() => {
  Promise.all([loadDeptAndSub(), loadOnlineDoctorList()])
})
</script>

<template>
  <view>
    <view class="header-container">
      <view class="dept_sub">
        <text @click="showDeptSubPicker = true">{{ deptSub }}</text>
        <u-icon name="arrow-down-fill" color="#b5b5b5" size="14"></u-icon>
      </view>
      <view class="job">
        <text @click="showJobPicker = true">{{ job }}</text>
        <u-icon name="arrow-down-fill" color="#b5b5b5" size="14"></u-icon>
      </view>
    </view>
    <view class="doctor-container">
      <view class="doctor" v-for="one in doctor" :key="one.id">
        <u-avatar :src="one.photo" size="45"></u-avatar>
        <view class="info">
          <view class="row">
            <text class="name">{{ one.name }}</text>
            <text class="job">{{ one.job }}</text>
            <button class="btn" @tap="createVideoDiagnoseHandle(one.doctorId)">问诊</button>
          </view>
          <view class="row">
            <text class="remark">{{ one.remark }}</text>
          </view>
          <view class="row">
            <text class="desc">{{ one.description }}</text>
          </view>
          <view class="row">
            <u-icon
              name="rmb-circle-fill"
              color="#ff0000"
              size="18"
              :label="one.price"
              labelColor="#ff0000"
              labelSize="18"
              top="1"
            ></u-icon>

            <u-icon
              name="clock-fill"
              color="#a0a0a0"
              size="18"
              label="问诊15分钟"
              labelColor="#a0a0a0"
              labelSize="16"
              top="1"
            ></u-icon>
          </view>
        </view>
      </view>
      <view v-if="doctor.length == 0">
        <u-empty mode="search" icon="http://cdn.uviewui.com/uview/empty/search.png"></u-empty>
      </view>
    </view>
    <u-picker
      :show="showDeptSubPicker"
      ref="DeptSubPicker"
      :columns="deptSubColumns"
      @confirm="confirmDeptSub"
      @change="changeDeptSub"
      @cancel="showDeptSubPicker = false"
    ></u-picker>

    <u-picker
      :show="showJobPicker"
      ref="JobPicker"
      :columns="jobColumns"
      @confirm="confirmJob"
      @cancel="showJobPicker = false"
    ></u-picker>
  </view>
</template>

<style lang="less">
@import url('doctor_list.less');
</style>
